package com.siyoumi.app.modules.redbook.service;

import com.siyoumi.app.entity.RedbookData;
import com.siyoumi.app.modules.redbook.service.data_handle.RedbookDataHandleCommentGood;
import com.siyoumi.app.modules.redbook.service.data_handle.RedbookDataHandleQuanCollect;
import com.siyoumi.app.modules.redbook.service.data_handle.RedbookDataHandleQuanGood;
import com.siyoumi.app.modules.redbook.vo.RedbookSetData;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;

public abstract class RedbookDataHandle {
    static public RedbookDataHandle of(Integer type) {
        RedbookDataHandle app = null;
        switch (type) {
            case 0: //朋友圈点赞
                app = new RedbookDataHandleQuanGood();
                break;
            case 1: //朋友圈收藏
                app = new RedbookDataHandleQuanCollect();
                break;
            case 2: //评论点赞
                app = new RedbookDataHandleCommentGood();
                break;

            default:
                XValidator.err(EnumSys.SYS.getR("类型未开发，" + type));
        }
        return app;
    }

    protected abstract XReturn handleAfter(RedbookSetData vo);

    protected XReturn handleCan(RedbookSetData vo) {
        return EnumSys.OK.getR();
    }

    final public XReturn handle(RedbookSetData vo) {
        XReturn r = handleCan(vo);
        if (r.err()) {
            return r;
        }

        RedbookData entityData = SvcRedbookData.getBean().getEntity(vo.getRdata_type(), vo.getRdata_id_src(), vo.getRdata_uid());
        return XApp.getTransaction().execute(status -> {
            if (vo.getAction() == 1) {
                //点赞 收藏
                if (entityData != null) {
                    return XReturn.getR(0, "操作成功");
                }

                RedbookData entityDataNew = new RedbookData();
                XBean.copyProperties(vo, entityDataNew);
                entityDataNew.setRdata_x_id(XHttpContext.getX());
                entityDataNew.setRdata_uix(XApp.getStrID());
                entityDataNew.setAutoID();
                SvcRedbookData.getApp().save(entityDataNew);
            } else {
                //取消点赞 取消收藏
                if (entityData == null) {
                    return XReturn.getR(0, "操作成功");
                }

                SvcRedbookData.getApp().delete(entityData.getRdata_id());
            }
            handleAfter(vo);

            return EnumSys.OK.getR();
        });
    }
}
